package com.ssh.controller;


import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssh.model.Dwzjson;
import com.ssh.model.User;
import com.ssh.service.IUserService;

@Controller
@RequestMapping(value={"/guoli/user"})
public class UserController {
	
	private IUserService userService;
	
	public IUserService getUserService() {
		return userService;
	}
	
	@Inject
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping(value={"/list"},method=RequestMethod.GET)
	public String showUsers(Model model){
		model.addAttribute("users", userService.findUsers());
		return "user/userlist";
	}
	
	@RequestMapping(value={"/add"},method=RequestMethod.GET)
	public String addUser(){
		return "user/useradd";
	}
	
	@ResponseBody
	@RequestMapping(value={"/add"},method=RequestMethod.POST)
	public Dwzjson addUser(@Validated User user, BindingResult br){
		if(br.hasErrors()){
			return new Dwzjson("300","failed","","","","");
		}
		userService.addUser(user);
		return new Dwzjson("200","successed","userlist","","closeCurrent","");
	}
	
	@RequestMapping(value={"/{id}/update"},method=RequestMethod.GET)
	public String updateUser(@PathVariable int id, Model model){
		User user = userService.getUser(id);
		if(user == null){
			return "error/error";
		}
		model.addAttribute("user", user);
		return "user/userupdate";
	}
	
	@ResponseBody
	@RequestMapping(value={"/{id}/update"},method=RequestMethod.POST)
	public Dwzjson updateUser(@PathVariable int id, @Validated User user, BindingResult br){
		if(br.hasErrors()){
			return new Dwzjson("300","failed","","","","");
		}
		User u = userService.getUser(id);
		u.setId(user.getId());
		u.setName(user.getName());
		u.setPassword(user.getPassword());
		userService.updateUser(u);
		return new Dwzjson("200","successed","userlist","","closeCurrent","");
	}
	
	@ResponseBody
	@RequestMapping(value={"/{id}/delete"})
	public Dwzjson deleteUser(@PathVariable int id){
		userService.deleteUser(id);
		return new Dwzjson("200","successed","userlist","","","");
	}
	
}
